<template>
  <div class="content-box">
    <div class="h-box">
      <div class="h-title stage">
        <i class="icon snowfont icon-xiangmuliebiao"></i>
        <p>配置事项清单</p>
      </div>
      <div class="h-title detail">
        <i class="icon snowfont icon-xiangmuliebiao"></i>
        <p>流程配置</p>
      </div>
    </div>
    <div class="set-box">
      <div class="stage-tabs">
        <div class="tab-h">项目阶段</div>
        <div class="tab-c">
          <el-tree
            ref="treeRefStage"
            :data="proStageList"
            :show-checkbox="hasCheckbox"
            :default-checked-keys="stageCheckedkeys"
            default-expand-all
            node-key="index"
            highlight-current
            :props="pageInfo.stageProps"
            :draggable="isEdit"
            :allow-drop="allowDrop"
            @node-click="node => handleChecked(node, 'stage')"
            @check-change="
              (node, checked) => handleChangeCheck(node, checked, 'stage')
            "
            @node-drop="
              (node, toNode, type) => handleDraged(node, toNode, type, 'stage')
            "
            @node-drag-start="dragStart"
          >
            <template #default="{ node, data }">
              <span
                v-if="!data.isEdit"
                class="custom-tree-node"
                :class="{ iRead: !isEdit }"
              >
                <span
                  class="flex1"
                  :class="{ error: errorStageIds.indexOf(data.index) > -1 }"
                  @dblclick="handleEditContent('stage', node, data)"
                  >{{ node.label }}</span
                >
                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  title="阶段下所有事项将全部删除, 确定删除吗？"
                  @confirm="handleDel('stage', node, data)"
                >
                  <template #reference>
                    <i class="icon snowfont icon-shanchu"></i>
                  </template>
                </el-popconfirm>
              </span>
              <span v-else class="custom-tree-node" :class="{ iRead: !isEdit }">
                <el-input
                  v-model.trim="data.projectStageName"
                  class="input-box"
                  :class="{ w106: hasCheckbox }"
                  placeholder="请输入阶段名称"
                  @blur="event => handleAddContent(event, 'stage', data)"
                ></el-input>
                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定删除该条记录吗？"
                  @confirm="handleDel('stage', node, data)"
                >
                  <template #reference>
                    <i class="icon snowfont icon-shanchu"></i>
                  </template>
                </el-popconfirm>
              </span>
            </template>
          </el-tree>
          <div class="opt-box" v-if="isEdit">
            <p
              v-if="editData.stage.show"
              class="custom-tree-node"
              :class="{ iRead: !isEdit }"
            >
              <el-input
                v-model.trim="editData.stage.content"
                class="wid142 input-box"
                placeholder="请输入阶段名称"
                @blur="event => handleAddContent(event, 'stage', false)"
              ></el-input>
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                icon="el-icon-info"
                icon-color="red"
                title="确定删除该条记录吗？"
                @confirm="handleDel('stage', node, data)"
              >
                <template #reference>
                  <i class="icon snowfont icon-shanchu"></i>
                </template>
              </el-popconfirm>
            </p>
            <div class="add-box">
              <i
                class="icon snowfont icon-tianjia"
                @click="handleAdd('stage')"
              ></i>
            </div>
          </div>
        </div>
      </div>
      <div class="task-tabs">
        <div class="tab-h">事项清单</div>
        <div class="tab-c">
          <el-tree
            ref="treeRefTask"
            :data="taskData"
            :show-checkbox="hasCheckbox"
            :default-checked-keys="taskCheckedkeys"
            default-expand-all
            node-key="index"
            highlight-current
            :props="pageInfo.taskProps"
            :draggable="isEdit"
            :allow-drop="allowDrop"
            @node-click="node => handleChecked(node, 'task')"
            @check-change="
              (node, checked) => handleChangeCheck(node, checked, 'task')
            "
            @node-drop="
              (node, toNode, type) => handleDraged(node, toNode, type, 'task')
            "
          >
            <template #default="{ node, data }">
              <span
                v-if="!data.isEdit"
                class="custom-tree-node"
                :class="{ iRead: !isEdit }"
              >
                <span
                  class="flex1"
                  :class="{ error: errorTaskIds.indexOf(data.index) > -1 }"
                  @dblclick="handleEditContent('task', node, data)"
                  >{{ node.label }}</span
                >
                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定删除该条记录吗？"
                  @confirm="handleDel('task', node, data)"
                >
                  <template #reference>
                    <i class="icon snowfont icon-shanchu"></i>
                  </template>
                </el-popconfirm>
              </span>
              <span v-else class="custom-tree-node" :class="{ iRead: !isEdit }">
                <el-input
                  v-model.trim="data.taskName"
                  class="input-box wid240"
                  :class="{ hasCheckbox: hasCheckbox }"
                  placeholder="请输入事项名称111"
                  @blur="event => handleAddContent(event, 'task', data)"
                ></el-input>
                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  icon="el-icon-info"
                  icon-color="red"
                  title="确定删除该条记录吗？"
                  @confirm="handleDel('task', node, data)"
                >
                  <template #reference>
                    <i class="icon snowfont icon-shanchu"></i>
                  </template>
                </el-popconfirm>
              </span>
            </template>
          </el-tree>
          <div class="opt-box" v-if="isEdit">
            <p
              v-if="editData.task.show"
              class="custom-tree-node"
              :class="{ iRead: !isEdit }"
            >
              <el-input
                v-model.trim="editData.task.content"
                class="wid256 input-box"
                placeholder="请输入事项名称"
                @blur="event => handleAddContent(event, 'task', false)"
              ></el-input>
              <el-popconfirm
                confirm-button-text="确定"
                cancel-button-text="取消"
                icon="el-icon-info"
                icon-color="red"
                title="确定删除该条记录吗？"
                @confirm="handleDel('task', node, data)"
              >
                <template #reference>
                  <i class="icon snowfont icon-shanchu"></i>
                </template>
              </el-popconfirm>
            </p>
            <div class="add-box">
              <i
                class="icon snowfont icon-tianjia"
                @click="handleAdd('task')"
              ></i>
            </div>
          </div>
        </div>
      </div>
      <div class="task-detail">
        <el-form
          :model="taskDetail"
          :rules="taskDetailRules"
          ref="taskDetailRef"
          label-width="80px"
          class="detail-box"
        >
          <template v-if="isEdit">
            <el-form-item label="事项名称" prop="taskName">
              <el-input
                v-model.trim="taskDetail.taskName"
                class="width-custom200 fs12"
              ></el-input>
            </el-form-item>
            <el-form-item label="流程类型" prop="approvalNodeCode">
              <el-select
                v-model="taskDetail.approvalNode"
                value-key="dicCode"
                class="width-custom200 fs12"
                @change="handleChangeNode"
              >
                <el-option
                  class="default-option"
                  v-for="item in temFlowList"
                  :label="item.dicValue"
                  :key="item.dicCode"
                  :value="item"
                ></el-option>
              </el-select>
              <el-popover
                v-if="taskDetail.approvalNode?.dicCode > 1129"
                popper-class="popoverBox"
                :width="750"
                placement="bottom"
                trigger="hover"
                :opacity="0"
              >
                <template #reference>
                  <el-avatar
                    id="popoverIcon"
                    style="margin-left: 10px"
                    :size="18"
                    ><p>?</p></el-avatar
                  >
                </template>
                <template #default>
                  <el-image
                    class="imageBox"
                    style="width: auto; height: auto"
                    :src="urlImage"
                  />
                </template>
              </el-popover>
            </el-form-item>
            <el-form-item label="预置信息">
              <div class="tinymce-box">
                <re-edit v-model="taskDetail.approvalForm"></re-edit>
              </div>
            </el-form-item>
            <el-form-item label="参考资料">
              <ecm-upload
                ref="ecmUploadRef"
                :files="defaultFileList"
                :docid="docid"
                @set-file="handleSuccess"
              ></ecm-upload>
            </el-form-item>
          </template>
          <template v-else>
            <el-form-item label="事项名称">
              <p class="detail-text min">
                {{ taskDetail.taskName }}
              </p>
            </el-form-item>
            <el-form-item label="流程类型">
              <p class="detail-text min">
                {{ taskDetail.approvalNodeName }}
              </p>
            </el-form-item>
            <el-form-item label="审批内容">
              <div
                v-html="taskDetail.approvalForm"
                class="read-content tinymce-box"
              ></div>
            </el-form-item>
            <el-form-item label="附件">
              <!-- <p
                class="text--info download-link subtext fs12"
                v-for="(item, index) in defaultFileList"
                :key="index"
                @click="downloadUrlFile(item.uuidFile, item.name)"
              >
                <el-link :underline="false">{{ item?.name }}</el-link>
              </p>
              <p
                class="text--info download-link subtext fs12"
                v-if="!defaultFileList || defaultFileList.length === 0"
              >
                -
              </p> -->
              <ecm-upload
                ref="ecmUploadRef"
                :files="defaultFileList"
                :docid="docid"
                @set-file="handleSuccess"
                :disabled="true"
                :hideText="true"
              ></ecm-upload>
            </el-form-item>
          </template>
          <!-- <el-button @click="save">测试按钮</el-button> -->
        </el-form>
      </div>
    </div>
  </div>
</template>
<script lang="ts">
import { ref, reactive, toRefs, watch, nextTick, computed } from "vue";
import ReEdit from "/@/components/ReEditor/index.vue";
import EcmUpload from "/@/components/ecmUpload/index.vue";
import {
  handlePreview,
  handleError,
  beforeAvatarUpload,
  acceptTypes,
  uploadUrl,
  onInitFileList,
  downloadUrlFile,
  onFilterFileData
} from "/@/utils/file";
import { storageLocal } from "/@/utils/storage";
import { postDictList } from "/@/api/home";
// import { url } from "inspector";
// import { string } from "vue-types";
// import { auto } from "@popperjs/core";
// import { constants } from "zlib";
export default {
  props: {
    mode: {
      type: String,
      default: "edit"
    },
    templateId: {
      type: [String, Number],
      default: ""
    },
    checkbox: {
      type: Boolean,
      default: false
    },
    data: {
      type: Array
    },
    type: {
      type: String,
      default: ""
    }
  },
  components: {
    ReEdit,
    EcmUpload
  },
  // emits: ["save"],
  setup(props) {
    let docid = window["ecmDocType"].project;
    const taskDetailRef = ref<HTMLFormElement | null>(null) as any;
    let treeRefStage = ref<HTMLElement | null>(null) as any;
    let treeRefTask = ref<HTMLElement | null>(null) as any;
    let state = reactive({
      pageInfo: {
        stageProps: {
          children: "children",
          label: "projectStageName"
        },
        taskProps: {
          children: "children",
          label: "taskName"
        }
      },
      taskDetailRules: {
        taskName: [
          {
            required: true,
            message: "请填写事项名称",
            trigger: ["blur", "change"]
          },
          {
            min: 3,
            max: 60,
            message: "长度在 3 到 60 个字符",
            trigger: ["blur", "change"]
          }
        ],
        approvalNodeCode: [
          { required: true, message: "请选择流程类型", trigger: "change" }
        ]
      },
      temFlowList: []
    });

    let proStageList = ref([...props.data]) as any; // 阶段+任务数据
    let activeStageId = ref(); // 当前选中的阶段
    let activeTaskId = ref(); // 当前选中的事项
    let taskData = ref([]);
    let errorStageIds = ref([]);
    let errorTaskIds = ref([]);
    let ecmUploadRef = ref(null);

    // 事项数据-表单
    let taskDetail = ref(
      proStageList.value[activeStageId.value || 0]?.proTmpTaskList[
        activeTaskId.value || 0
      ] || {
        taskName: "",
        approvalForm: "",
        approvalNode: {
          dicCode: "",
          dicValue: ""
        },
        approvalNodeCode: "",
        approvalNodeName: "",
        approvalNodeTmpAttachmentArr: []
      }
    );

    // 阶段、事项编辑暂存
    let editData = reactive({
      stage: {
        show: false,
        content: ""
      },
      task: {
        show: false,
        content: ""
      }
    });
    let defaultFileList = ref([]);
    let isEdit = ref(props.mode === "edit");
    let hasCheckbox = ref(props.checkbox);
    let stageCheckedkeys = ref([]);
    let taskCheckedkeys = ref([]);
    let urlImage = ref("");
    let tasksMapObj = ref({});
    // 拖拽的元素index
    let dragOpt = ref(null);

    watch(
      () => [props.data, props.checkbox],
      ([newVal, newCheckbox]) => {
        let list = newVal as any;
        list.forEach((item, index) => {
          let tasksIndex = [];
          item.index = new Date().getTime() + "s" + index;
          item.isEdit = item.isEdit || false;
          item.proTmpTaskList = item.proTmpTaskList || [];
          item.proTmpTaskList.forEach((task, i) => {
            task.index = new Date().getTime() + "t" + index + i;
            task.isEdit = task.isEdit || false;
            task.approvalNode = task.approvalNode || {
              dicCode: task.approvalNodeCode,
              dicValue: task.approvalNodeName
            };
            !tasksIndex.includes(task.index) && tasksIndex.push(task.index);
          });
          tasksMapObj.value[item.index] = [...tasksIndex];
        });
        proStageList.value = [...list];
        activeStageId.value = list[0]?.index;
        activeTaskId.value = list[0]?.proTmpTaskList[0]?.index;
        if (newCheckbox) {
          stageCheckedkeys.value = Object.keys(tasksMapObj.value) || [];
          taskCheckedkeys.value = tasksMapObj.value[activeStageId.value];
        }
        setdata(proStageList.value, activeTaskId.value, activeStageId.value);
        nextTick(() => {
          treeRefTask.value.setCurrentKey(activeTaskId.value, false);
          treeRefStage.value.setCurrentKey(activeStageId.value, false);
        });
      }
    );

    // watch(
    //   () => props.type,
    //   nV => {
    //     if (nV === "A") {
    //       initTemFlowTypeList("thd_flow_template_ab");
    //     } else if (nV === "B") {
    //       initTemFlowTypeList("thd_flow_template_ab");
    //     } else if (nV === "C") {
    //       initTemFlowTypeList("thd_flow_template_ab");
    //     }
    //   }
    // );

    const setdata = (data, activeTaskId, activeStageId?) => {
      if (activeStageId) {
        taskData.value = data.find(
          item => item.index === activeStageId
        )?.proTmpTaskList;
      }
      taskDetail.value = taskData.value.find(
        item => item.index === activeTaskId
      ) || {
        taskName: "",
        approvalForm: "",
        approvalNode: {
          dicCode: "",
          dicValue: ""
        },
        approvalNodeCode: "",
        approvalNodeName: "",
        approvalNodeTmpAttachmentArr: []
      };
      defaultFileList.value = onInitFileList(
        taskDetail.value.approvalNodeTmpAttachmentArr
      );
      urlImage.value = new URL(
        `../../../../assets/processCharts/${taskDetail.value.approvalNode?.dicCode}.png`,
        import.meta.url
      ).href;
      if (ecmUploadRef.value) {
        ecmUploadRef.value.defaultFileList = defaultFileList.value;
        ecmUploadRef.value.fileArr = defaultFileList.value;
      }
    };

    const setchecked = (data, activeStageId, setDom) => {
      stageCheckedkeys.value = Object.keys(data) || [];
      taskCheckedkeys.value = data[activeStageId] || [];
      if (setDom) {
        nextTick(() => {
          treeRefTask.value.setCheckedKeys(taskCheckedkeys.value, false);
        });
      }
    };

    const handleAdd = async type => {
      // 先校验表单，如果表单不完整不允许切换
      // let isValid = await validForm(type);
      // if (!isValid) {
      //   return false;
      // }
      editData[type].show = true;
      editData[type].content = "";
    };

    const handleEditContent = async (type, node, data) => {
      // 先校验表单，如果表单不完整不允许切换
      // let isValid = await validForm(type);
      // if (!isValid) {
      //   return false;
      // }
      if (type === "stage") {
        getRowData(proStageList.value, activeStageId.value).isEdit = true;
      } else {
        let list = getRowData(
          proStageList.value,
          activeStageId.value
        ).proTmpTaskList;
        getRowData(list, data.index).isEdit = true;
      }
    };

    // 输入框失去焦点时，保存当前编辑的值
    const handleAddContent = (event, type, data) => {
      let value = event?.target.value;
      editData[type].show = false;
      if (value) {
        if (type === "stage") {
          let editStageUnit = data
            ? data
            : {
                index: null,
                isEdit: false,
                proTmpTaskList: [],
                projectStageName: ""
              };
          editStageUnit.projectStageName = value;
          editStageUnit.isEdit = false;
          editStageUnit.proTmpTaskList = data.proTmpTaskList || [];
          if (!data.index) {
            editStageUnit.index = new Date().getTime() + "s";
            proStageList.value.push({ ...editStageUnit });
          }
          activeStageId.value = editStageUnit.index;
          activeTaskId.value = editStageUnit.proTmpTaskList[0]?.index;
          setdata(proStageList.value, activeTaskId.value, activeStageId.value);
          nextTick(() => {
            treeRefStage.value.setCurrentKey(activeStageId.value, false);
          });
        } else {
          // 事项
          const editTaskUnit = data
            ? data
            : {
                index: null,
                isEdit: false,
                projectTmpId: props.templateId,
                taskName: "",
                approvalNodeCode: "",
                approvalNodeName: "",
                approvalForm: "",
                approvalNodeTmpAttachment: "",
                approvalNodeTmpAttachmentArr: []
              };
          let taskList = getRowData(
            proStageList.value,
            activeStageId.value
          ).proTmpTaskList;
          editTaskUnit.taskName = value;
          editTaskUnit.isEdit = false;
          if (!data.index) {
            editTaskUnit.index = new Date().getTime() + "t";
            taskList.push({ ...editTaskUnit });
          }
          activeTaskId.value = editTaskUnit.index;
          setdata(proStageList.value, activeTaskId.value, "");
          nextTick(() => {
            treeRefTask.value.setCurrentKey(activeTaskId.value, false);
          });
        }
      }
    };

    // 根据index获取相应数据
    const getRowData = (data, index) => {
      let obj = data.find(item => item.index === index);
      return obj;
    };

    const handleDel = (type, node, data) => {
      // 删除一条数据
      if (type === "stage") {
        let deleteIndex = proStageList.value.findIndex(
          item => item.index === data.index
        );
        // 删除该阶段下所有的数据
        proStageList.value.splice(deleteIndex, 1);
        // 将选中项置为0
        activeStageId.value = proStageList.value[0]?.index;
      } else {
        let deleteIndex = getRowData(
          proStageList.value,
          activeStageId.value
        ).proTmpTaskList.findIndex(item => item.index === data.index);
        getRowData(
          proStageList.value,
          activeStageId.value
        ).proTmpTaskList.splice(deleteIndex, 1);
      }
      activeTaskId.value = getRowData(
        proStageList.value,
        activeStageId.value
      ).proTmpTaskList[0]?.index;
      setdata(proStageList.value, activeTaskId.value, activeStageId.value);
      nextTick(() => {
        if (type === "stage") {
          treeRefStage.value.setCurrentKey(activeStageId.value, false);
        }
      });
    };

    // const validForm = async type => {
    //   // 先校验表单，如果表单不完整不允许切换
    //   const isValid = await new Promise(resolve =>
    //     taskDetailRef.value.validate(resolve)
    //   );
    //   if (!isValid) {
    //     nextTick(() => {
    //       if (type === "task") {
    //         treeRefTask.value.setCurrentKey(activeTaskId.value, false);
    //       } else {
    //         treeRefStage.value.setCurrentKey(activeStageId.value, false);
    //       }
    //     });
    //   }
    //   return isValid;
    // };

    const handleChecked = async (node, type) => {
      // 先校验表单，如果表单不完整不允许切换
      // let isValid = await validForm(type);
      // if (!isValid && type === "task") {
      //   return false;
      // }
      if (type === "stage") {
        activeStageId.value = node.index;
        activeTaskId.value = getRowData(
          proStageList.value,
          activeStageId.value
        ).proTmpTaskList[0]?.index;
        setdata(proStageList.value, activeTaskId.value, activeStageId.value);
        setchecked(tasksMapObj.value, activeStageId.value, false);
        nextTick(() => {
          treeRefTask.value.setCurrentKey(activeTaskId.value, false);
        });
      } else {
        activeTaskId.value = node.index;
        setdata(proStageList.value, activeTaskId.value, "");
      }
    };

    const dragStart = node => {
      dragOpt.value = node.data.index;
    };

    // 勾选模板节点
    const handleChangeCheck = (node, checked, type) => {
      if (!hasCheckbox.value) {
        return;
      }
      let index = node.index;
      if (type === "stage") {
        // 拖拽后，需要手动设置阶段模板选中, 但要避免将全部任务事项选中，若为拖拽操作的id且是选中，且该节点已经被选中时，就直接返回；
        if (index === dragOpt.value && checked) {
          let isSame = Object.keys(tasksMapObj.value).indexOf(index) > -1;
          if (isSame) {
            return;
          }
        }
        let list = getRowData(proStageList.value, index).proTmpTaskList;
        if (checked) {
          // tasksMapObj.value[index] = [...Array(list.length).keys()];
          tasksMapObj.value[index] = [...list.map(item => item.index)];
        } else {
          delete tasksMapObj.value[index];
        }
        setchecked(tasksMapObj.value, activeStageId.value, true);
      } else {
        let tasklist = tasksMapObj.value[activeStageId.value] || [];
        if (checked) {
          !tasklist.includes(index) && tasklist.push(index);
        } else {
          let indexs = tasklist.indexOf(index);
          tasklist.splice(indexs, 1);
        }
        setchecked(tasksMapObj.value, activeStageId.value, true);
      }
    };

    const allowDrop = (draggingNode, dropNode, type) => {
      // 不能拖拽到级别里面
      if (type === "inner") {
        return false;
      } else {
        return true;
      }
    };

    // 拖拽
    const handleDraged = (node, toNode, dragType, type) => {
      if (type === "stage") {
        activeStageId.value = node.data.index;
        activeTaskId.value = getRowData(
          proStageList.value,
          activeStageId.value
        ).proTmpTaskList[0]?.index;
        let setCheckFlag =
          Object.keys(tasksMapObj.value).indexOf(activeStageId.value) > -1;
        let obj = setCheckFlag
          ? tasksMapObj.value[activeStageId.value]
          : undefined;

        setdata(proStageList.value, activeTaskId.value, activeStageId.value);
        nextTick(() => {
          treeRefStage.value.setCurrentKey(activeStageId.value, false);
          treeRefTask.value.setCurrentKey(activeTaskId.value, false);
          if (obj) {
            tasksMapObj.value[activeStageId.value] = obj;
            setchecked(tasksMapObj.value, activeStageId.value, false); // 拖拽后，阶段会被置为非选中
          }
        });
      } else {
        activeTaskId.value = node.data.index;
        // 拖拽后会取消取消选中。处理：如果是已选中的节点，需要手动改变选中状态
        if (
          tasksMapObj.value[activeStageId.value].indexOf(activeTaskId.value) >
          -1
        ) {
          tasksMapObj.value[activeStageId.value].push(activeTaskId.value);
        }
        setdata(proStageList.value, activeTaskId.value, activeStageId.value);
        nextTick(() => {
          treeRefTask.value.setCurrentKey(activeTaskId.value, false);
        });
      }
    };

    // 文件相关
    const handleRemove = (file, fileList) => {
      defaultFileList.value = fileList;
    };

    const handleSuccess = fileList => {
      defaultFileList.value = fileList;
      let list = getRowData(
        proStageList.value,
        activeStageId.value
      ).proTmpTaskList;
      let task = getRowData(list, activeTaskId.value);
      task.approvalNodeTmpAttachment = JSON.stringify(
        onFilterFileData(defaultFileList.value)
      );

      task.approvalNodeTmpAttachmentArr = onFilterFileData(
        defaultFileList.value
      );

      if (ecmUploadRef.value) {
        ecmUploadRef.value.defaultFileList = fileList;
      }
    };

    // 处理模板数据
    const handleTemplateData = hasCheckbox => {
      if (!hasCheckbox) {
        return proStageList.value;
      }
      // 根据map保存数据 tasksMapObj
      let proStageListChecked = [];
      let keys = Object.keys(tasksMapObj.value);
      proStageList.value.forEach(item => {
        if (keys.includes(String(item.index))) {
          let obj = { ...item };
          let list = obj.proTmpTaskList;
          let tasksChecked = tasksMapObj.value[item.index];
          let finalList = [];
          list.forEach(task => {
            if (tasksChecked.includes(task.index)) {
              finalList.push(task);
            }
          });
          obj.proTmpTaskList = [...finalList];
          proStageListChecked.push(obj);
        }
      });
      return proStageListChecked;
    };

    const save = async () => {
      let dataArr = handleTemplateData(hasCheckbox.value);
      let flag = true;
      errorStageIds.value.length = 0;
      errorTaskIds.value.length = 0;
      if (dataArr.length === 0) {
        return Promise.reject("请配置事项清单");
      }
      dataArr.forEach(item => {
        if (!item.proTmpTaskList || !item.proTmpTaskList.length) {
          flag = false;
          errorStageIds.value.push(item.index);
        } else {
          let list = item.proTmpTaskList;
          list.forEach(li => {
            if (!li.taskName || !li.approvalNodeCode) {
              flag = false;
              errorStageIds.value.push(item.index);
              errorTaskIds.value.push(li.index);
            }
          });
        }
      });
      if (!flag) {
        return Promise.reject("项目阶段数据或流程配置数据不完整");
      }
      return Promise.resolve(dataArr);
    };

    // const handleReset = (): void => {
    //   taskDetailRef.value.resetFields();
    //   taskDetail.value.approvalForm = "";
    //   taskDetail.value.approvalForm = "";
    //   defaultFileList.value = [];
    // };

    // 流程类型变化时，给code，value赋值
    const handleChangeNode = val => {
      taskDetail.value.approvalNodeName = val?.dicValue;
      taskDetail.value.approvalNodeCode = val?.dicCode;
      urlImage.value = new URL(
        `../../../../assets/processCharts/${taskDetail.value.approvalNode?.dicCode}.png`,
        import.meta.url
      ).href;
    };

    // 流程类型
    const initTemFlowTypeList = async dicType => {
      try {
        state.temFlowList = [];
        const { data } = await postDictList({
          dicType
        });
        state.temFlowList = data || [];
      } catch (err) {
        console.log(err);
      }
    };
    initTemFlowTypeList("thd_flow_template_ab");
    const uploadHeaders = computed(() => {
      return {
        Authorization: storageLocal.getItem("info")?.accessToken,
        loginMethod: "PC"
      };
    });

    return {
      docid,
      taskDetailRef,
      treeRefStage,
      treeRefTask,
      ...toRefs(state),
      isEdit,
      hasCheckbox,
      urlImage,

      // 文件相关
      defaultFileList,
      handlePreview,
      handleError,
      beforeAvatarUpload,
      acceptTypes,
      uploadUrl,
      onInitFileList,
      downloadUrlFile,
      onFilterFileData,
      uploadHeaders,
      ecmUploadRef,
      // 组件数据
      proStageList,
      taskData,
      taskDetail,
      editData,
      stageCheckedkeys,
      taskCheckedkeys,
      errorStageIds,
      errorTaskIds,

      // 组件操作
      allowDrop,
      handleAdd,
      handleChecked,
      handleChangeCheck,
      dragStart,
      // handleReset,
      handleChangeNode,
      handleDel,
      handleDraged,
      save,
      initTemFlowTypeList,
      handleAddContent,
      handleEditContent,

      handleRemove,
      handleSuccess
    };
  }
};
</script>

<style lang="scss" scoped>
.content-box {
  .h-box {
    display: flex;
    height: 24px;
    margin-bottom: 8px;
    .h-title {
      display: flex;
      align-items: center;
      &.stage {
        width: 448px;
      }
      &.detail {
        flex: 1;
      }
      i {
        font-size: 20px;
        margin-right: 10px;
        color: #8895b7;
      }
      p {
        font-size: 14px;
        font-weight: bold;
      }
    }
  }

  .set-box {
    display: flex;
    align-items: stretch;
    min-height: 566px;
    .stage-tabs {
      width: 162px;
      border: 1px solid #e4e8f2;
      border-right: none;
      border-radius: 4px 0 0 4px;
    }
    .task-tabs {
      width: 278px;
      border: 1px solid #e4e8f2;
      margin-right: 8px;
      border-radius: 0 4px 4px 0;
    }
    .task-detail {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      border: 1px solid #e4e8f2;
      border-radius: 4px;
      .fs12.el-input--small {
        font-size: 12px;
      }
      .fs12:deep {
        .el-input--small {
          font-size: 12px;
        }
      }
      .detail-box {
        padding: 16px 16px 8px;
        .upload-box {
          position: relative;
          .el-upload__tip {
            display: inline-block;
            line-height: 16px;
            margin-top: 0;
            color: #8895b7;
            padding: 8px 8px 0;
          }
        }
      }
      .opt-btns {
        height: 48px;
        padding: 10px 16px;
        border-top: 1px solid #e4e8f2;
        background-color: #fdfdff;
        border-radius: inherit;
      }
      &:deep .el-button.el-button--small {
        min-height: 28px;
        height: 28px;
        padding: 5px 11px;
        font-size: 12px;
      }
    }
    .tab-h {
      height: 32px;
      line-height: 32px;
      padding-left: 10px;
      padding-right: 10px;
      background: #f7f9fd;
      font-weight: bold;
      font-size: 12px;
    }
    .tab-c {
      font-size: 12px;
      .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        .flex1 {
          flex: 1;
          &.error {
            color: #e45d5d;
          }
        }
        i {
          display: none;
          font-size: 16px;
          color: #5298ff;
          margin-left: 4px;
        }
        .input-box {
          font-size: 12px;
          width: 124px;
        }
        .w106 {
          width: 106px;
        }
        .wid142 {
          width: 142px;
        }
        .wid240 {
          width: 240px;
          &.hasCheckbox {
            width: 220px;
          }
        }
        .wid256 {
          width: 256px;
        }
      }
      .opt-box {
        padding-left: 10px;
      }
      .add-box {
        width: 20px;
        height: 20px;
        background-color: #5298ff;
        border-radius: 4px;
        cursor: pointer;
        margin-top: 8px;
        // margin-left: 10px;
        text-align: center;
        line-height: 20px;
        i {
          color: #fdfdff;
        }
      }
    }
    &:deep .el-tree {
      .el-tree__empty-block {
        display: none;
      }
      .el-tree-node__content {
        padding-right: 6px;
        height: 28px;
        &:hover {
          .custom-tree-node i {
            display: inline-block;
          }
          .custom-tree-node.iRead i {
            display: none;
          }
        }
        .el-tree-node__expand-icon {
          width: 10px;
          margin-left: 0;
          margin-right: 0;
        }
        .el-tree-node__label {
          overflow: hidden;
          text-overflow: ellipsis;
        }
        & > label.el-checkbox {
          margin-right: 6px;
          .el-checkbox__inner {
            width: 12px;
            height: 12px;
            border-radius: 1px;
            &:after {
              left: 3px;
              top: 0px;
            }
          }
        }
        // .el-input--small .el-input__inner {
        //   height: 24px;
        //   line-height: 24px;
        //   padding-left: 4px;
        //   padding-right: 4px;
        // }
      }
    }
    &:deep .el-input--small .el-input__inner {
      height: 24px;
      line-height: 24px;
      padding-left: 4px;
      padding-right: 4px;
    }
    &:deep .el-form {
      font-size: 12px;
      .el-form-item--small .el-form-item__label {
        line-height: 28px;
        font-size: 12px;
        padding-right: 8px;
      }
      .el-form-item__content {
        min-height: 28px;
        line-height: 28px;
        font-size: 12px;
        .el-input__inner {
          height: 28px;
          line-height: 28px;
          padding-left: 6px;
          padding-right: 6px;
        }
      }
    }
  }

  .detail-text {
    display: inline-block;
    min-width: 200px;
    height: 32px;
    line-height: 20px;
    padding: 6px 12px;
    background-color: #fdfdff;
    color: #8895b7;
    &.w100 {
      width: 100%;
    }
    &.min {
      padding: 6px;
      height: 28px;
      line-height: 16px;
    }
  }
  #popoverIcon {
    position: absolute;
    margin-top: 5px;
    :hover {
      cursor: pointer;
    }
    p {
      font-size: 14px;
      font-weight: 600;
    }
  }
}
</style>

<style lang="scss">
.el-popover.popoverBox {
  max-width: 1200px;
}

.imageBox {
  align-self: center;
  width: 600px;
  height: 300px;
}
</style>
